package com.yd.spark.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.google.common.collect.Maps;

public class DispatchInfoHandlerImpl implements Serializable{
	private static final long serialVersionUID = 4453465154297251593L;
	
	public static final String[] fieldNames = new String[] { "datetime", "null", "service_order_id", "dispatch_count",
			"response_count", "accept_count", "flag", "dispatch_time", "decision_time", "contribution",
			"expect_decision_time", "dispatch_template_id", "template_snapshot", "status", "dispatch_type",
			"decision_type", "round", "batch", "create_time", "update_time", "estimate_time", "can_dispatch_count",
			"user_id", "user_level", "user_name", "user_gender", "add_price_redispatch", "add_price_info",
			"decision_driver_id", "decision_car_type_id", "bidding_id", "bidding_rate" };

	public static String parseToJson(String line) throws IOException {
		Map<String, String> jsonBuild = Maps.newHashMap();

		// log分割成13份, 取出前12个字段
		String[] fields = line.split(" ", 13);
		for (int i = 0; i < 12; i++) {
			jsonBuild.put(fieldNames[i], fields[i]);
		}
		line =  fields[12];
		// 继续将第13份分割成2份,先取出 dispatch_snapshot(第13个)字段
		if(line.charAt(0) == ' '){
			line="{} "+line.substring(1);
		}
		fields = line.split("} ", 2);
		jsonBuild.put(fieldNames[12], fields[0] + "}");
		//将dispatch_snapshot之后的内容分成12份,取出前11(第14-24)个字段
		fields = fields[1].split(" ", 12);
		for (int i = 0; i < 11; i++) {
			jsonBuild.put(fieldNames[i + 13], fields[i]);
		}
		//取出剩下的8(第25-32)个字段,注要先从后向前取7个,剩下的都是user_name
		fields = fields[11].split(" ", -1);
		int extra = fields.length - 8; //理论上fields.length一定大于等于8
		for(int i=7;i > 0; i--){
			jsonBuild.put(fieldNames[i + 24], fields[i + extra]);
		}
		//把user_name拼接起来
		String user_name = StringUtils.join(fields, " ", 0, extra+1);
		jsonBuild.put(fieldNames[24], user_name);
//		System.out.println(jsonBuild.size());
		return JsonUtils.toJson(jsonBuild);
	}

	public static void main(String[] args) throws IOException {
		String log = "2016-11-08_17:19:22  6350256544182042223 4 0 0 0 1478534341 0 400 1478536141 3877  1 1 1 2 1 1478534318 1478534341 1800 0 15362631 1 李先生 M 0 - 0 0 6350256537553732689 0.00";
		
		parseToJson(log);
		Path path = Paths.get("dispatch_info.txt");
		BufferedReader in = java.nio.file.Files.newBufferedReader(path, Charsets.UTF_8);
		String line = null;
		while ((line = in.readLine()) != null) {
			String[] fields = line.split(" ", -1);
			if (fields.length != 32) {
//				System.err.println(fields.length + " : "+ line);
				System.err.println(parseToJson(line));
			}

		}
		IOUtils.closeQuietly(in);
	}
}
